package shopping.demo.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import shopping.demo.annotation.ApiIdempotent;
import shopping.demo.code.ResponseCode;
import shopping.demo.entities.Order;
import shopping.demo.entities.response.EntitiesResponse;
import shopping.demo.entities.response.Response;
import shopping.demo.service.OrderCommitService;
import shopping.demo.service.OrderService;

import java.util.List;


@RestController
@RequestMapping("/orders")
public class OrderController {
    @Autowired
    private OrderService orderService;
    @Autowired
    private OrderCommitService orderCommitService;
    private Logger logger = LoggerFactory.getLogger(Logger.class);

    //返回的是所有用户的所有订单（针对管理员）
    @GetMapping("/list")
    public String findAll() {
        List<Order> orders = orderService.findAll();
        return JSON.toJSONString(orders);
    }

    //创建订单
    @PostMapping(value = "/order",consumes = "application/json")
    public String createOrder(@RequestBody JSONObject jsonObject) throws Exception{
        Long uid = jsonObject.getLong("uid");
        Integer gid = jsonObject.getInteger("gid");
        Integer count = jsonObject.getInteger("count");
        Integer price = jsonObject.getInteger("price");

        Order order = orderService.createOrder(uid,gid,count,price);
        return JSONObject.toJSONString(new EntitiesResponse(order,ResponseCode.ORDER_SUCCESS.getCode(),ResponseCode.GOODS_SUCCESS.getMsg()));
    }
    //提交订单
    @ApiIdempotent
    @PatchMapping("/order")
    public String changeStatus(@RequestBody JSONObject jsonObject) throws Exception{
        Order order = JSONObject.parseObject(jsonObject.toJSONString(),Order.class);
        orderCommitService.commitOrder(order);
        return JSONObject.toJSONString(new Response(ResponseCode.ORDER_SUCCESS.getCode(),ResponseCode.ORDER_SUCCESS.getMsg()));
    }

    //删除订单（针对管理员）
    @DeleteMapping(value = "/order",consumes = "application/json")
    public String deleteOrder(@RequestBody JSONObject jsonObject) throws Exception{
        String oid = jsonObject.getString("oid");
        orderService.deleteById(oid);
        return JSONObject.toJSONString(new Response(ResponseCode.ORDER_SUCCESS.getCode(),ResponseCode.ORDER_SUCCESS.getMsg()));
    }

//    //返回的是用户的所有订单（针对用户）
//    @GetMapping("/order/userId")
//    public String findByUserId(Long uid) {
//        List<Order> orders = orderService(uid);
//        JSONObject response = new JSONObject();
//        response.put("orders",orders);
//        response.put("code",ResponseCode.ORDER_SUCCESS.getCode());
//        response.put("msg",ResponseCode.ORDER_SUCCESS.getMsg());
//        return "user_orderList";
//    }



}
